/*
 * @Author: zhangyang
 * @Date: 2022-03-22 17:04:40
 * @LastEditTime: 2022-03-23 09:47:37
 * @Description: 手写 LRU
 */
export class LRU {
  private pool = new Map();
  private keyMap = new Map<any, number>();
  /**
   * 初始化
   * @param maxLength 默认最大容积为 3
   */
  constructor(public maxLength = 3) {}

  getUnUsedKey() {
    // 过滤已经删除的(权值为 0)
    const entries = [...this.keyMap.entries()].filter((item) => item[1]);
    // 按权值升序排序
    entries.sort((a, b) => a[1] - b[1]);
    // 返回权值最低的键
    return entries[0][0];
  }

  put(key: any, value: any) {
    if (this.pool.size >= this.maxLength) {
      const key = this.getUnUsedKey();
      this.keyMap.set(key, 0);
      this.pool.delete(key);
    }
    const priority = this.keyMap.get(key);
    if (priority) {
      this.keyMap.set(key, priority + 1);
    } else {
      this.keyMap.set(key, 1);
    }
    this.pool.set(key, value);
  }

  get(key: any) {
    const priority = this.keyMap.get(key);
    if (priority) {
      this.keyMap.set(key, priority + 1);
    }
    return this.pool.get(key);
  }

  all() {
    return this.pool;
  }

  delete(key: any) {
    this.keyMap.set(key, 0);
    return this.pool.delete(key);
  }

  clear() {
    this.keyMap.clear();
    this.pool.clear();
  }
}